<template>
  <div class="order-review-page">
    <div class="page-header">
      <h2>订单审核</h2>
      <el-button type="primary" @click="handleRefresh">
        <el-icon><Refresh /></el-icon>
        刷新
      </el-button>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filterForm" inline>
        <el-form-item label="业务类型">
          <el-select
            v-model="filterForm.business_type"
            placeholder="请选择"
            clearable
            style="width: 150px"
          >
            <el-option label="案件委托" :value="1" />
            <el-option label="诉讼指导" :value="2" />
            <el-option label="法务顾问套餐" :value="3" />
            <el-option label="非诉专项" :value="4" />
            <el-option label="律师函" :value="5" />
            <el-option label="开具发票" :value="6" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核类型">
          <el-select
            v-model="filterForm.review_type"
            placeholder="请选择"
            clearable
            style="width: 150px"
          >
            <el-option label="到账审核" :value="1" />
            <el-option label="合同回收审核" :value="2" />
            <el-option label="开票审核" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select
            v-model="filterForm.status"
            placeholder="请选择"
            clearable
            style="width: 150px"
          >
            <el-option label="待审核" :value="1" />
            <el-option label="审核通过" :value="2" />
            <el-option label="审核驳回" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="关键词">
          <el-input
            v-model="filterForm.keyword"
            placeholder="客户名称/订单编号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="16" class="stats-row">
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-item">
            <div class="stat-label">待审核</div>
            <div class="stat-value pending">{{ stats.pending }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-item">
            <div class="stat-label">已通过</div>
            <div class="stat-value approved">{{ stats.approved }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-item">
            <div class="stat-label">已驳回</div>
            <div class="stat-value rejected">{{ stats.rejected }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-item">
            <div class="stat-label">审核总额</div>
            <div class="stat-value amount">¥{{ formatAmount(stats.total_amount) }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table :data="tableData" v-loading="loading" stripe>
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="order_no" label="订单编号" min-width="150" />
        <el-table-column prop="customer_name" label="客户名称" min-width="150" />
        <el-table-column prop="business_type_text" label="业务类型" width="120" />
        <el-table-column prop="review_type_text" label="审核类型" width="120" />
        <!-- 合同文件 -->
        <el-table-column prop="attachment" label="合同文件" width="150">
          <template #default="scope">
            <div v-if="scope.row.attachment && scope.row.attachment.length">
              <el-button type="text" size="small" @click="handleDownload(scope.row.attachment[0])">
                {{ scope.row.attachment.length }}个文件
              </el-button>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="金额" width="120">
          <template #default="{ row }">
            <span class="amount-text">¥{{ formatAmount(row.amount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="user_name" label="申请人" width="100" />
        <el-table-column prop="status" label="审核状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ row.status_text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="提交时间" width="160" />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleDetail(row)">查看详情</el-button>
            <el-button v-if="row.status === 1" type="success" link @click="handleApprove(row, 2)">
              通过
            </el-button>
            <el-button v-if="row.status === 1" type="danger" link @click="handleApprove(row, 3)">
              驳回
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 审核详情抽屉 -->
    <GlobalDrawer
      v-model="detailVisible"
      title="订单审核详情"
      size="80%"
      :show-footer-buttons="false"
    >
      <div v-if="currentReview">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单编号">
            {{ currentReview.order_no }}
          </el-descriptions-item>
          <el-descriptions-item label="客户名称">
            {{ currentReview.customer_name }}
          </el-descriptions-item>
          <el-descriptions-item label="业务类型">
            {{ currentReview.business_type_text }}
          </el-descriptions-item>
          <el-descriptions-item label="审核类型">
            {{ currentReview.review_type_text }}
          </el-descriptions-item>
          <el-descriptions-item label="审核金额">
            <span class="amount-text">¥{{ formatAmount(currentReview.amount) }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="申请人">
            {{ currentReview.user_name }}
          </el-descriptions-item>
          <el-descriptions-item label="提交时间">
            {{ currentReview.create_time }}
          </el-descriptions-item>
          <el-descriptions-item label="审核状态">
            <el-tag :type="getStatusType(currentReview.status)">
              {{ currentReview.status_text }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="审核人" v-if="currentReview.reviewer_name">
            {{ currentReview.reviewer_name }}
          </el-descriptions-item>
          <el-descriptions-item label="审核时间" v-if="currentReview.review_time">
            {{ currentReview.review_time }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 附件列表 -->
        <div
          v-if="currentReview.attachment && currentReview.attachment.length > 0"
          style="margin-top: 20px"
        >
          <h4>附件</h4>
          <el-table :data="currentReview.attachment" border>
            <el-table-column prop="name" label="文件名称" />
            <el-table-column label="操作" width="120">
              <template #default="{ row }">
                <el-button type="primary" link @click="handleDownload(row)">下载</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div v-if="currentReview.review_remark" style="margin-top: 20px">
          <h4>审核备注</h4>
          <p>{{ currentReview.review_remark }}</p>
        </div>
      </div>
    </GlobalDrawer>

    <!-- 审核对话框 -->
    <el-dialog
      v-model="approveVisible"
      :title="approveStatus === 2 ? '审核通过' : '审核驳回'"
      width="500px"
    >
      <el-form :model="approveForm" label-width="80px">
        <el-form-item label="审核备注">
          <el-input
            v-model="approveForm.remark"
            type="textarea"
            :rows="4"
            placeholder="请输入审核备注"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="approveVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmApprove" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import { Refresh } from '@element-plus/icons-vue'
  import { reviewApi } from '@/api/crm'
  import type { Review } from '@/types/crm'
  import GlobalDrawer from '@/components/common/GlobalDrawer.vue'

  const loading = ref(false)
  const submitting = ref(false)
  const tableData = ref<any[]>([])
  const detailVisible = ref(false)
  const approveVisible = ref(false)
  const currentReview = ref<any>(null)
  const approveStatus = ref(2)

  const filterForm = reactive({
    business_type: '',
    review_type: '',
    status: '',
    keyword: '',
  })

  const pagination = reactive({
    current: 1,
    size: 20,
    total: 0,
  })

  const approveForm = reactive({
    remark: '',
  })

  const stats = ref({
    pending: 0,
    approved: 0,
    rejected: 0,
    total: 0,
    total_amount: 0,
  })

  // 格式化金额
  const formatAmount = (amount: number) => {
    return amount ? amount.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',') : '0.00'
  }

  // 获取审核列表
  const getReviewList = async () => {
    loading.value = true
    try {
      const params = {
        page: pagination.current,
        limit: pagination.size,
        business_type: filterForm.business_type,
        review_type: filterForm.review_type,
        status: filterForm.status,
        keyword: filterForm.keyword,
      }
      const res = await reviewApi.list(params)

      tableData.value = res.data.list || []
      pagination.total = res.data.total || 0
    } catch (error) {
      console.error('获取审核列表失败:', error)
      ElMessage.error('获取审核列表失败')
    } finally {
      loading.value = false
    }
  }

  // 获取统计信息
  const getStatistics = async () => {
    try {
      const res = await reviewApi.statistics()
      stats.value = res.data
    } catch (error) {
      console.error('获取统计信息失败:', error)
    }
  }

  // 获取状态类型
  const getStatusType = (status: number) => {
    const types: Record<number, string> = {
      1: 'warning',
      2: 'success',
      3: 'danger',
    }
    return types[status] || 'info'
  }

  // 查看详情
  const handleDetail = async (row: any) => {
    try {
      const res = await reviewApi.detail(row.id)
      currentReview.value = res.data
      detailVisible.value = true
    } catch (error) {
      console.error('获取详情失败:', error)
      ElMessage.error('获取详情失败')
    }
  }

  // 审核
  const handleApprove = (row: any, status: number) => {
    currentReview.value = row
    approveStatus.value = status
    approveForm.remark = ''
    approveVisible.value = true
  }

  // 确认审核
  const confirmApprove = async () => {
    submitting.value = true
    try {
      await reviewApi.approve({
        id: currentReview.value.id,
        status: approveStatus.value,
        remark: approveForm?.remark || '',
      })

      ElMessage.success(approveStatus.value === 2 ? '审核通过' : '审核驳回')
      approveVisible.value = false
      getReviewList()
      getStatistics()
    } catch (error) {
      console.error('审核失败:', error)
      ElMessage.error('审核失败')
    } finally {
      submitting.value = false
    }
  }

  // 下载附件
  const handleDownload = (file: any) => {
    // 实现文件下载逻辑
    window.open(file.url, '_blank')
  }

  // 搜索
  const handleSearch = () => {
    pagination.current = 1
    getReviewList()
  }

  // 重置
  const handleReset = () => {
    filterForm.business_type = ''
    filterForm.review_type = ''
    filterForm.status = ''
    filterForm.keyword = ''
    pagination.current = 1
    getReviewList()
  }

  // 刷新
  const handleRefresh = () => {
    getReviewList()
    getStatistics()
  }

  // 分页大小改变
  const handleSizeChange = (size: number) => {
    pagination.size = size
    pagination.current = 1
    getReviewList()
  }

  // 当前页改变
  const handleCurrentChange = (current: number) => {
    pagination.current = current
    getReviewList()
  }

  onMounted(() => {
    getReviewList()
    getStatistics()
  })
</script>

<style scoped>
  .order-review-page {
    padding: 20px;
  }

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }

  .page-header h2 {
    margin: 0;
    font-size: 20px;
    font-weight: 500;
  }

  .filter-card {
    margin-bottom: 16px;
  }

  .stats-row {
    margin-bottom: 16px;
  }

  .stat-item {
    text-align: center;
  }

  .stat-label {
    font-size: 14px;
    color: #909399;
    margin-bottom: 8px;
  }

  .stat-value {
    font-size: 28px;
    font-weight: bold;
    color: #303133;
  }

  .stat-value.pending {
    color: #e6a23c;
  }

  .stat-value.approved {
    color: #67c23a;
  }

  .stat-value.rejected {
    color: #f56c6c;
  }

  .stat-value.amount {
    color: #409eff;
    font-size: 24px;
  }

  .amount-text {
    color: #409eff;
    font-weight: 500;
  }

  .pagination {
    margin-top: 20px;
    text-align: right;
  }
</style>
